package com.atguigu.dga.util;

import org.apache.hadoop.hive.ql.lib.DefaultGraphWalker;
import org.apache.hadoop.hive.ql.lib.Dispatcher;
import org.apache.hadoop.hive.ql.parse.ASTNode;
import org.apache.hadoop.hive.ql.parse.HiveParser;
import org.apache.hadoop.hive.ql.parse.ParseDriver;

import java.util.Collections;

public class SqlUtil {

    //遍历查询sql语法树
    public static void parseSQL(String sql, Dispatcher dispatcher)throws Exception{
        //将sql解析成ast
        ParseDriver parseDriver = new ParseDriver();
        ASTNode parse = parseDriver.parse(sql);
        //取第一个TOK_QUERY作为根节点
        while (parse.getType()!= HiveParser.TOK_QUERY){
            parse = (ASTNode) parse.getChild(0);
        }
        //遍历语法树,并对每一个节点进行处理
        DefaultGraphWalker defaultGraphWalker = new DefaultGraphWalker(dispatcher);
        defaultGraphWalker.startWalking(Collections.singleton(parse),null);

    }

    public static void main(String[] args) throws Exception {
       String sql = "select * from c where c.id = 101";
       parseSQL(sql,null);
    }


    //替换字符
    public static String filterUnsafeSql(String input) {
        if (input == null) {
            return null;
        }

        // 替换 MySQL 中可能导致 SQL 注入的特殊字符
        return input.replace("\\", "\\\\")
                .replace("'", "\\'")
                .replace("\"", "\\\"")
                .replace("\b", "\\b")
                .replace("\n", "\\n")
                .replace("\r", "\\r")
                .replace("\t", "\\t")
                .replace("\u001A", "\\Z")
                .replace("%", "\\%")
                .replace("_", "\\_");
    }
}
